import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/findUserServlet")
public class findUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应的格式为JSON格式
        resp.setContentType("application/json;charset=utf-8");
        //这么设置以后,就不用再在html页面中设置type = json了

        //resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        Map<String, Object> map = new HashMap<>();
        if ("WAN".equals(username)) {
            map.put("userExist", true);
            map.put("msg", "有人已经注册过这个名字了");
        } else {
            map.put("userExist", false);
            map.put("msg", "可用");
        }

        //将map转为json
        ObjectMapper mapper = new ObjectMapper();
        //将数据传输到客户端
        mapper.writeValue(resp.getWriter(), map);

        //因为是ajax的调用,所以不需要再跳转

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
